package com.xmim.core.session;


import com.xmim.core.exception.SessionrException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultSessionManager<T extends Session> implements SessionManager {
    private Map<String, T> sessionMap = new ConcurrentHashMap<>();
    private List<SessionListener<T>> sessionListeners = new ArrayList<>();

    @Override
    public SessionManager addSessionListener(SessionListener sessionListener) {
        sessionListeners.add(sessionListener);
        return this;
    }

    @Override
    public void destroySession(String sessionId) {
        T session = sessionMap.get(sessionId);
        if (session == null) {
            return;
        }
        for (SessionListener<T> sessionListener : sessionListeners) {
            sessionListener.event(EventType.DESTROY, session);
        }
        try {
            session.close();
            sessionMap.remove(sessionId);
        } catch (SessionrException e) {
            e.printStackTrace();
        }
    }

    @Override
    public SessionManager addSession(String sessionId, Session session) {
        sessionMap.put(sessionId, (T) session);
        for (SessionListener sessionListener : sessionListeners) {
            sessionListener.event(EventType.ADDED, session);
        }
        return this;
    }


    @Override
    public Session getSession(String sessionId) {
        Session session = null;
        for (SessionListener sessionListener : sessionListeners) {
            session = sessionListener.event(EventType.FIND, null);
        }
        if (session != null) {
            return session;
        }
        return sessionMap.get(sessionId);
    }

    @Override
    public boolean hasSession(String sessionId) {
        return sessionMap.containsKey(sessionId);
    }

    public Map<String, T> getSessionMap() {
        return sessionMap;
    }
}
